<template>
  <div class="scanQRCode">
    <div v-if="showQRcode.showcode" class="scanQRCode-body" id="scan"></div>
    <button v-else type="button" @click="clickEvent">扫码成功</button>
  </div>
</template>

<script>
import Vue from 'vue'
let scan = null
export default {
  data () {
    return {
      randomid: '',
      showQRcode: {
        showcode: true
      }
    }
  },

  methods: {
    clickEvent () {
      // 带着扫码信息，去做自己想要的操作
    },
    // 开始识别
    startScan() {
      if (!window.plus) return
      // 创建Barcode扫码控件
      this.startRecognize()
      setTimeout(() => {
        scan.start()
      }, 200)
    },
    // 创建扫描控件对象
    startRecognize() {
      var _this = this
      if (!window.plus) return

      scan = null
      scan = new window.plus.barcode.Barcode(
        'scan',
        [window.plus.barcode.QR],
        {
          frameColor: '#f08700',
          scanbarColor: '#f08700'
        }
      )

      /**
      * 扫码识别成功事件
      * type: ( Number ) 必选 识别到的条码类型
      * result: ( String ) 必选 识别到的条码数据
      */
      scan.onmarked = (type, result, file) => {
        let text = '未知: '
        switch (type) {
          case window.plus.barcode.QR:
            text = 'QR: '
            break
          case window.plus.barcode.EAN13:
            text = 'EAN13: '
            break
          case window.plus.barcode.EAN8:
            text = 'EAN8: '
            break
          default:
            text = '其他: '
            break
        }
        _this.randomid = result
        _this.showQRcode.showcode = false
        if (result !== '' || result !== null || result !== undefined) {
          _this.$nextTick(() => {
            Vue.set(_this.showQRcode, 'showcode', false)
            scan.close()
          })
        }
        console.log(text + result)
      }
    },
    camerapermissions () {
      var Build = window.plus.android.importClass('android.os.Build')
      var Manifest = window.plus.android.importClass('android.Manifest')
      var MainActivity = window.plus.android.runtimeMainActivity()
      // var context=main.getApplicationContext(); // 未用到,在此仅供参考
      var ArrPermissions = [
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA
      ]

      function PermissionCheck (permission) {
        if (Build.VERSION.SDK_INT >= 23) {
          if (MainActivity.checkSelfPermission(permission) === -1) {
            return false
          }
        }
        return true
      }

      function PermissionChecks (Arr) {
        var HasPermission = true
        for (var index in Arr) {
          var permission = Arr[index]
          // 如果此处没有权限,则是用户拒绝了
          if (!PermissionCheck(permission)) {
            HasPermission = false
            break
          }
        }
        return HasPermission
      }

      function PermissionRequest (Arr) {
        var REQUEST_CODE_CONTACT = 101
        if (Build.VERSION.SDK_INT >= 23) {
          MainActivity.requestPermissions(Arr, REQUEST_CODE_CONTACT)
        }
      }

      // 如果没有权限，则申请
      if (!PermissionChecks(ArrPermissions)) {
        PermissionRequest(ArrPermissions)
      } else { // 如果拥有权限，那么干点啥吧^_^
        // .......
      }
    },
    qrcode () {
      var _this = this
      if (window.plus) {
        var _s = window.plus.navigator.checkPermission('camera')
        if (_s === 'authorized') {
          _this.startScan()
        } else if (_s === 'undetermined') {
          var msg = '请在应用权限里设置允许使用相机权限'
          window.plus.nativeUI.alert(msg, function (e) {
            if (window.plus.os.name === 'iOS') {
              window.plus.runtime.openURL('app-settings:CAMERA')
            } else {
              _this.camerapermissions()
              _this.$nextTick(() => {
                _this.$forceUpdate()
                _this.$router.replace('/mine')
              })
            }
          })
        } else {
          if (window.plus.os.name === 'iOS') {
            window.plus.runtime.openURL('app-settings:CAMERA')
          } else {
            var main = window.plus.android.runtimeMainActivity()
            var Intent = window.plus.android.importClass('android.content.Intent')
            var Build = window.plus.android.importClass('android.os.Build')
            var Uri = window.plus.android.importClass('android.net.Uri')
            var intent = new Intent()
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            if (Build.VERSION.SDK_INT >= 9) { // 系统8.0以上的
              intent.setAction('android.settings.APPLICATION_DETAILS_SETTINGS')
              intent.setData(Uri.fromParts('package', main.getPackageName(), null))
            } else if (Build.VERSION.SDK_INT <= 8) { // 系统8.0以下的
              intent.setAction(Intent.ACTION_VIEW)
              intent.setClassName('com.android.settings', 'com.android.setting.InstalledAppDetails')
              intent.putExtra('com.android.settings.ApplicationPkgName', main.getPackageName())
            }
            main.startActivity(intent)
            _this.$nextTick(() => {
              _this.$forceUpdate()
              _this.$router.replace('/mine')
            })
          }
        }
      }
    }

  },
  beforeRouteEnter (to, from, next) {
    next((vm) => {
      // 调取二维码扫码
      vm.qrcode()
    })
  },
  beforeDestroy () {
    if (!window.plus) return
    scan.cancel()
    scan.close()
  }
}
</script>
